﻿using AllServer.Core;
using AllServer.Core.Util;
using Furion;
using Furion.VirtualFileServer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;

namespace AllServer.Proxy.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            // 配置选项
            services.AddProjectOptions();

            //Nginx/IIS 无法获取正确客户端 IP 问题
            services.Configure<ForwardedHeadersOptions>(options =>
            {
                //options.ForwardedHeaders = ForwardedHeaders.All;

                // 若上面配置无效可尝试下列代码，比如在 IIS 中
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                //options.KnownNetworks.Clear();
                //options.KnownProxies.Clear();
            });

            //防止 Session ID 改变或 Session 失效
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => false; // 默认为true，改为false
                options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
            });

            //日志跟踪使用唯一ID
            services.AddConsoleFormatter(options =>
            {
                options.WithTraceId = true;
            });
            //注册文件日志组件
            services.AddComponent<FileLogServiceComponent>();

            //注入sqlsugar
            services.AddSqlSugar();

            services.AddJwt<JwtHandler>();

            services.AddCorsAccessor();

            //审计日志
            services.AddMvcFilter<RequestAuditFilter>();

            // Json序列化设置
            static void SetNewtonsoftJsonSetting(JsonSerializerSettings setting)
            {
                setting.DateFormatHandling = DateFormatHandling.IsoDateFormat;
                setting.DateTimeZoneHandling = DateTimeZoneHandling.Local;
                setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
                setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
            };

            services.AddControllersWithViews()
                       .AddNewtonsoftJson(options => SetNewtonsoftJsonSetting(options.SerializerSettings))
            .AddInjectWithUnifyResult<SpeciallyResultProvider>();

            services.AddRemoteRequest();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            // 添加规范化结果状态码，需要在这里注册
            app.UseUnifyResultStatusCodes();

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
